package com.homework.ch10;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/14
 * @Description:
 */
class Clerk{
    //管理资源：成员变量、成员方法（生产、消费、通信、锁）
    //成员变量productCount：产品数 0

    private int productCount=10;
    private final int MaxproductCount=20;
    //生产产品，进货：produceProduct()
    //如果小于20个，就生产，通知消费者notifyAll
    // 如果大于20个就等待
    public synchronized void  produceProduct(){
        if(productCount>=MaxproductCount){
            try {
                System.out.println(Thread.currentThread().getName()+"库存太多："+productCount);
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            productCount++;
            System.out.println(Thread.currentThread().getName()+"生产了"+productCount);
            notifyAll();
        }
    }
    //消费产品，卖货：consumerProduct()
    //如果产品大于0，就消费，通知生产者notifyAll
    //如果小于等于0，就等待
    public synchronized void consumerProduct(){
        if(productCount<=0){
            try {
                System.out.println(Thread.currentThread().getName()+"没货了");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            productCount--;
            System.out.println(Thread.currentThread().getName()+"消费了还有"+productCount);
            this.notifyAll();
        }
    }

}
//生产者 extends/implement 线程
class Producer extends  Thread{
    //店员对象  使用关系
    //构造器：线程名称，店员对象
    //重写run
    //循环{ 每隔100毫秒就生产货物：店员对象.produceProduct()}
    Clerk clerk;

    public Producer(String name, Clerk clerk) {
        super(name);
        this.clerk = clerk;
    }
    @Override
    public void run(){
        while (true) {
            try {
                Thread.sleep(100);
                clerk.produceProduct();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//消费者 线程
class Customer extends Thread{
    //店员对象  使用关系
    //构造器：线程名称，店员对象
    //重写run
    //循环{每隔200毫秒就消费货物：店员对象.consumerProduct()}
    Clerk clerk;

    public Customer(String name, Clerk clerk) {
        super(name);
        this.clerk = clerk;
    }
    @Override
    public void run(){
        while (true) {
            try {
                Thread.sleep(50);
                clerk.consumerProduct();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Test8{
    public static void main(String[] args) {
        Clerk clerk=new Clerk();
        Producer p1=new Producer("一号生产线",clerk);
        Producer p2=new Producer("二号生产线",clerk);
        Customer c1=new Customer("消费者1",clerk);
        Customer c2=new Customer("消费者2",clerk);
        Customer c3=new Customer("消费者3",clerk);
        Customer c4=new Customer("消费者4",clerk);
        p1.start();
        p2.start();
        c1.start();
        c2.start();
        c3.start();
        c4.start();
    }
}
